import 'whatwg-fetch'

export const base = `http://chart.0755yicai.cn`

let parseParam = function (data) {
  if (data === null || data === '' || JSON.stringify(data) === '{}') return ''
  let u = function (param, key, encode) {
    let paramStr = ''
    let t = typeof (param)
    if (t === 'string' || t === 'number' || t === 'boolean') {
      paramStr += '&' + key + '=' + ((encode === null || encode) ? encodeURIComponent(param) : param)
    } else {
      for (let i in param) {
        let k = key == null ? i : key + (param instanceof Array ? '[' + i + ']' : '.' + i)
        paramStr += u(param[i], k, encode)
      }
    }
    return paramStr
  }
  return '?' + u(data).substr(1)
}

export const repeater = (vm, n, d) => {
  if (n !== 'getZgsRecharges' && n !== 'getZgsWithdraws') vm.$Loading.start()
  const promist = new Promise(function (resolve, reject) {
    vm.$api[n](d).then(response => {
      let warning = response.headers.get('License-Warning')
      // let warn = response.headers.get('License-Warn')
      if (n !== 'getZgsRecharges' && n !== 'getZgsWithdraws') vm.$Loading.finish()
      if (response.status !== 200) {
        vm.$Loading.error()
        switch (response.status) {
          case 400:
            vm.$Message.error('参数错误')
            break
          case 401:
            vm.$Message.error('登录信息失效')
            break
          case 402:
            vm.$Message.error('保留有效ChargeTo头响应')
            break
          case 403:
            vm.$Message.error('禁止访问')
            vm.$router.push({
              name: 'error-403'
            })
            break
          case 404:
            vm.$Message.error('请求资源不存在')
            vm.$router.push({
              name: 'error-404'
            })
            break
          case 405:
            vm.$Message.error('用户在Request-Line字段定义的方法不允许')
            break
          case 406:
            vm.$Message.error('根据用户发送的Accept拖，请求资源不可访问')
            break
          case 407:
            vm.$Message.error('用户必须首先在代理服务器上得到授权')
            break
          case 408:
            vm.$Message.error('客户端没有在用户指定的饿时间内完成请求')
            break
          case 409:
            vm.$Message.error('对当前资源状态，请求不能完成')
            break
          case 429:
            vm.$Message.error('请求数量过多，请稍后重试。。')
            break
          case 500:
            vm.$Message.error('服务器遇到错误，无法完成请求')
            break
          case 501:
            vm.$Message.error('未实现')
            break
          case 502:
            vm.$Message.error('网关错误')
            break
          case 503:
            vm.$Message.error('由于超载或停机维护，服务器目前无法使用，一段时间后可能恢复正常')
            break
        }
      }
      if (response.status === 401) {
        sessionStorage.clear()
        vm.$router.push({
          name: 'home'
        })
      } else {
        response.json().then(responseJson => {
          resolve(responseJson)
        })
      }
      if (response.status === 500) {
        response.text().then(responseJson => {
          let regex = /<pre.*?>(.*?)<\/pre>/ig
          let result = regex.exec(responseJson)
          vm.$Notice.error({
            title: '错误',
            desc: result[1]
          })
          resolve(false)
        })
      }
      if (response.status === 503) {
        if (warning !== null) {
          let testStr = unescape(warning.replace(/\\u/g, '%u'))
          let reg = /^["|'](.*)["|']$/g
          let test = testStr.replace(reg, '$1')
          let id = 0
          if (test === '未授权的软件副本') id = 1
          if (test === '软件试用期已满') id = 2
          if (test === '软件授权有效期已满') id = 3
          vm.$router.push({name: 'error-503', params: {id: id}})
        }
      }
    }).catch(error => {
      if (error === 'TypeError: Failed to fetch') {
        vm.$Message.error('服务器无法连接')
      }
      vm.$Loading.error()
    })
  })
  return promist
}

/**
 * 验证码
 * @param params params
 */
export const getCaptcha = params => fetch(`${base}/captcha${parseParam(params)}`, {
  method: 'GET',
  cache: 'no-cache'
})

/**
 * 登陆
 * @param params params
 */
export const login = params => fetch(`${base}/login`, {
  method: 'POST',
  body: JSON.stringify(params),
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 * 短信验证码
 * @param params params
 */
export const smsCode = params => fetch(`${base}/SmsCode`, {
  method: 'POST',
  body: JSON.stringify(params),
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 *注册
 * @param params params
 */
export const register = params => fetch(`${base}/register`, {
  method: 'POST',
  body: JSON.stringify(params),
  headers: {
    'Content-Type': 'application/json'
  }
})

/**
 * 历史记录
 * @param params params
 */
export const getHistory = params => fetch(`${base}/Api/Vip/History/1${parseParam(params)}`, {
  method: 'GET',
  // credentials: '*',
  // body: params,
  headers: {
    'Authorization': sessionStorage.token
  }
})

/**
 * 获取点卡列表
 * @param params params
 */
export const getCards = params => fetch(`${base}/Api/Vip/Cards${parseParam(params)}`, {
  method: 'GET',
  // credentials: '*',
  // body: params,
  headers: {
    'Authorization': sessionStorage.token
  }
})

/**
 *购买点卡下单
 * @param params params
 */
export const buyCard = params => fetch(`${base}/Api/Vip/BuyCard`, {
  method: 'POST',
  body: JSON.stringify(params),
  headers: {
    'Authorization': sessionStorage.token,
    'Content-Type': 'application/json'
  }
})

/**
 * 获取订单列表
 * @param params params
 */
export const getBuyList = params => fetch(`${base}/Api/Vip/BuyList${parseParam(params)}`, {
  method: 'GET',
  // credentials: '*',
  // body: params,
  headers: {
    'Authorization': sessionStorage.token
  }
})

/**
 * 获取收款二维码
 * @param params params
 */
export const getAliPay = params => fetch(`${base}/Api/Vip/AliPay`, {
  method: 'GET',
  // credentials: '*',
  // body: params,
  headers: {
    'Authorization': sessionStorage.token
  }
})

/**
 * 获取有效期
 * @param params params
 */
export const getCardExpire = params => fetch(`${base}/Api/Vip/CardExpire/1`, {
  method: 'GET',
  // credentials: '*',
  // body: params,
  headers: {
    'Authorization': sessionStorage.token
  }
})
